#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
    int m, n;
    int dx[4] = { 0, 0, 1, -1 };
    int dy[4] = { 1, -1, 0, 0 };
    bool vis[310][310] = { 0 };
    int ret = 0;
    int numIslands(vector<vector<char>>& g) {
        m = g.size(), n = g[0].size();
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++) {
                if (!vis[i][j] && g[i][j] == '1') {
                    ret++;
                    vis[i][j] = true;
                    dfs(g, i, j);
                }
            }
        return ret;
    }

    void dfs(vector<vector<char>>& g, int i, int j) {

        for (int k = 0; k < 4; k++) {
            int x = i + dx[k], y = j + dy[k];
            if (x >= 0 && y >= 0 && x < m && y < n && !vis[x][y] && g[x][y] == '1') {
                vis[i][j] = true;
                dfs(g, x, y);
            }
        }

    }
};

int main() {
    vector<vector<char>> g = {
        {'1', '1', '1', '1', '0'},
        {'1', '1', '0', '1', '0'},
        {'1', '1', '0', '0', '0'},
        {'0', '0', '0', '0', '0'}
    };
    Solution s;
    s.numIslands(g);
	return 0;
}